#!/bin/sh
#
# login -- login lab with a specified method
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#

uname | grep -q MINGW && PWD_OPT="-W"
TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd $PWD_OPT)"
. "$TOP_DIR/tools/docker/config" $* >/dev/null

verify_login()
{
  method=$1
  match=0

  echo $method | grep -q '[a-z]'
  if [ $? -eq 0 ]; then
    for l in $LOGIN_METHODS
    do
      number=`expr $number + 1`

      if [ "$l" = "$method" ]; then
        match=1
        return 0
      fi
    done
  else
    total=`echo "$LOGIN_METHODS " | tr -d -c ' ' | wc -c`
    if [ $method -le $total ]; then
      number=$method
      return 0
    fi
  fi

  return 1
}

login_config()
{
  # List available login methods
  echo "Please choose one of the login methods:"
  echo
  echo $LOGIN_METHODS | tr ' ' '\n' | nl -v 1
  echo
  
  # Let user choose one
  read -p 'LOG: Choose the login method: ' method

  [ -z "$method" ] && echo "\nERR: No method specified.\n" && exit 1
  
  number=0
  verify_login $method
  [ $? -ne 0 ] && echo "\nERR: No valid method specified.\n" && exit 1
  
  LOGIN_METHOD=`echo $LOGIN_METHODS | tr ' ' '\n' | head -$number | tail -1`
  echo "\n     $number\t$LOGIN_METHOD\n"
  
  LOGIN=$LOGIN_METHOD
  
  set_var LOGIN
} # login_config

# Get login method in this order: command argument, environment variable and .login_method configuration
# If the first argument is valid lab, use the second one as login method argument.
if [ -n "$1" ]; then
  LAB=$1
  [ -n "$LAB" ] && ls "$CONFIGS_DIR" | tr -s ' ' | tr ' ' '\n' | grep -q ^$LAB$
  if [ $? -eq 0 ]; then
    LOGIN=$2
  else
    LOGIN=$1
  fi
fi

if [ "$LOGIN" != "list" ]; then
  if [ -n "$LOGIN" ]; then
    # Not login if none specified
    [ "$LOGIN" = "none" ] && exit 0

    verify_login $LOGIN
    if [ $? -ne 0 ]; then
      echo "\nERR: $LOGIN is not valid login method, avilable methods:\n"
      echo "    $LOGIN_METHODS.\n"
      exit 1
    fi
    set_var LOGIN
  else
    get_var LOGIN none
  fi
fi

[ "$LOGIN" = "none" -o "$LOGIN" = "list" ] && login_config && set_var LOGIN

LOGIN_TOOL="tools/docker/$LOGIN"

echo "LOG: Available login methods:"
echo
echo "     $LOGIN_METHODS" | egrep --color "[^a-z]$LOGIN"
echo
echo "LOG: Switch to another method:"
echo
echo "     $0 LOGIN_METHOD" | sed -e "s%$TOP_DIR/%%g"
echo
echo "LOG: Running '$LOGIN_TOOL'"
echo
$LOGIN_TOOL
